package com.cy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/consumer")
public class RestConsumerController {
    @Autowired
    private RestTemplate loadBalancedRestTemplate;
    @DeleteMapping("/{id}")
    public String doDeleteById(@PathVariable Long ...id){
        String idArrays = Arrays.toString(id);
        idArrays=idArrays.substring(1,idArrays.length()-1);
        String url=String.format("http://%s/provider/%s","sca-provider",idArrays);
        ResponseEntity<String> requestEntity=
        loadBalancedRestTemplate.exchange(url, HttpMethod.DELETE,null,String.class);
        return "delete ok"+"  "+requestEntity.getBody();
    }
    @PostMapping
    public String doCreate(@RequestBody Map<String,Object> map){
        String url=String.format("http://%s/provider","sca-provider");
        String s = loadBalancedRestTemplate.postForObject(url, map, String.class);
        System.out.println(s);
        return "map is create";
    }
    @PutMapping
    public Map doUpdate(@RequestBody Map<String,Object> map){
        String url=String.format("http://%s/provider","sca-provider");
        //loadBalancedRestTemplate.put(url,map);
        HttpEntity requstEntity=new HttpEntity(map);
        ResponseEntity<Map> responseEntity = loadBalancedRestTemplate.exchange(url, HttpMethod.PUT, requstEntity, Map.class);
        return responseEntity.getBody();
    }
}
